<template>
  <div class="clearfix">
    <a-upload :action="api.file.upload" listType="picture-card" width="50px"  v-bind="$attrs" :data="params" :disabled="this.$attrs.disabled" :headers="accessToken" :fileList="fileList" accept=".png,.jpg,.jpeg" @preview="handlePreview" @change="handleChange">
      <div v-if="fileList.length < fileMax&&crop==false&&!this.$attrs.disabled">
        <a-icon type="plus"/>
      </div>

      <div v-if="fileList.length < fileMax&&crop==true&&!this.$attrs.disabled" @click.stop="showCopper">
        <a-icon type="plus"/>
      </div>
    </a-upload>

    <viewer :visible="previewVisible" v-show='previewVisible' :images="fileList" @inited="inited" class="viewer" ref="viewer">
        <img v-for="file in fileList" :src="file.url+'/original'" :key="file" :data-source="file.url+'/original'">
    </viewer>

<!--    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">-->
<!--      <img alt="example" style="width: 100%" :src="previewImage" v-viewer/>-->
<!--    </a-modal>-->

    <div style="color: #b7b7b5;width: 260px" v-if="fileMax>1&&shopTip==true">最多上传{{fileMax}}张图片 {{tip}}</div>

    <f-upload-copper ref="copperModal" @handleSuccess="handleChange" :cropOption="cropOption" v-if="crop"></f-upload-copper>
  </div>
</template>

<script>
  import Vue from 'vue'
  import { getPreviewImage } from '../utils/util'
  import FUploadCopper from './UploadCropper'

  export default {
    name: 'uploadImages',
    components: { FUploadCopper },
    model: {
      prop: 'value',
      event: 'change.value'
    },
    props: {
      value: {
        type: [String, Array],
        default: ''
      },
      fileSize: {
        default: 2048
      },
      tip: {
        type: String,
        default: ''
      },
      busId: {
        type: String,
        default: ''
      },
      busType: {
        type: String,
        default: ''
      },
      shopTip: {
        type: Boolean,
        default: true
      },
      //取值形式(url,json)
      valueType: {
        type: String,
        default: 'url'
      },
      //是否开启裁剪上传
      crop: {
        type: Boolean,
        default: false
      },
      //裁剪框大小
      cropSize: {
        type: [String, Array],
        default: 'small'
      },
      cropTip: {
        type: String,
        default: ''
      },
      size: {
        type: Number,
        default: 55
      },
      iconSize: {
        type: Number,
        default: 22
      },
      width: {
        type: Number,
        default: null
      },
      height: {
        type: Number,
        default: null
      },
      delIconSize: {
        type: Number,
        default: 20
      },
      tip: {
        type: String,
        default: ''
      },
      //真实删除
      realRemove: {
        type: Boolean,
        default: false
      },
      fileMax: {
        type: Number,
        default: 3
      },
      fileUrl: {
        type: [String, Array],
        default: ''
      },
      defaultList: {
        type: Array,
        default: () => []
      },
      cropOption: {
        type: [Object],
        default: () => ({
          cropWidth: 200,
          width: '750px',
          height: '300px',
          cropAreaHeight: '300px',
          cropHeight: 200,
          enlarge: 1,
          remark: ''
        })
      }
    },
    computed: {
      fileMaxSize: {
        get: function() {
          if (this.fileSize > 1024) {
            this.sizeUnit = 'M'
            return Number(this.fileSize / 1024).toFixed(2)
          } else {
            this.sizeUnit = 'KB'
            return this.fileSize
          }
        },
        cropOption: {
          get: function() {
            if (typeof this.cropSize == 'string') {
              if (this.cropSize === 'small') {
                return {
                  cropWidth: 200,
                  cropHeight: 200,
                  cropAreaHeight: '300px',
                  height: '300px',
                  width: '750px',
                  enlarge: 1,
                  cropTip: this.cropTip
                }
              }
              if (this.cropSize === 'default') {
                return {
                  cropWidth: 280,
                  cropHeight: 210,
                  cropAreaHeight: '400px',
                  height: '50%',
                  width: '900px',
                  enlarge: 2,
                  cropTip: this.cropTip
                }
              }
            } else {
              return {
                cropWidth: this.cropSize[0],
                cropHeight: this.cropSize[1],
                cropAreaHeight: '400px',
                height: '50%',
                width: '45%',
                enlarge: 1,
                cropTip: this.cropTip
              }
            }
          }
        }
      }
    },
    watch: {
      uploadList() {
        this.showUpload = this.uploadList.length < this.fileMax
      },
      busId(value) {
        this.params.busId = value
      },
      value(value) {
        console.info('图片地址：', value)
        if (value != '' && typeof value == 'string') {
          if (value.indexOf('[{') > -1) {
            this.fileList = JSON.parse(value)
          } else {
            // 解决上传时重复添加第一张图问题
            if (this.isUpload == false || this.fileMax == 1) {
              if (this.fileMax > 1) {
                this.fileList.push({
                  uid: '-1',
                  name: 'slider.png',
                  status: 'done',
                  url: value
                })
              } else {
                this.fileList = [{
                  uid: '-1',
                  name: 'slider.png',
                  status: 'done',
                  url: value
                }]
              }
            }

          }
        }
        if (this.value != '' && typeof this.value == 'object') {
          if (value) {
            this.fileList = value
          }
        }
        if (this.value == '') {
          this.fileList = []
        }
      }
    },
    data() {
      const token = Vue.ls.get('Access-Token')
      return {
        accessToken: {
          Authorization:  token
        },
        sizeUnit: 'KB',
        loading: false,
        viewImage: false,
        viewImg: {},
        showUpload: false,
        loading: false,
        isUpload: false,
        visible: false,
        params: {
          busId: this.busId,
          busType: this.busType
        },
        fileIds: [],
        removeIds: [],
        files: [],
        uploadList: [],
        previewVisible: false,
        previewImage: '',
        fileList: []
      }
    },
    methods: {
      init() {

      },
      inited (viewer) {
        this.$viewer = viewer
      },
      showCopper() {
        this.$refs.copperModal.showModal()
      },
      handleCancel() {
        this.previewVisible = false
      },
      // 图片预览
      handlePreview(file) {
        let i=0;
        this.fileList.forEach(function(val, index, arr){
          if(file.url==val.url){
             i=index;
          }
        });
        this.$viewer.view(i)
        //this.previewImage = getPreviewImage(file.response ? file.response.data.url : file.url)
        //this.previewVisible = true
      },
      // 上传 删除事件
      handleChange({ file, fileList, event }) {
        console.info('event1', event)
        console.info('fileList1', fileList)
        console.info('file1', file)
        this.isUpload = true
        this.fileList = fileList
        let me = this
        this.fileIds = []
        this.files = []
        if (file.status != 'uploading') {
          console.info('event1', event)
          console.info('fileList1', fileList)
          console.info('file1', file)
          fileList.map(function(file) {
            if (file.response) {
              me.files.push({
                uid: file.response.data.uid,
                name: file.response.data.name,
                url: file.response.data.url
              })
              //新上传文件ID
              me.fileIds.push(file.response.data.uid)
            } else {
              me.files.push({
                uid: file.uid,
                name: file.name,
                url: file.url
              })
            }
          })
          if (file.status == 'removed') {
            let fileId = ''
            if (file.response) {
              fileId = file.response.data.uid
            } else {
              fileId = file.uid
            }
            this.removeIds.push(fileId)
            if (this.realRemove == true && fileId != '') {
              this.http.del(this, {
                url: this.api.file.remove,
                data: {
                  fileIds: fileId
                }
              })
            }
          }
          if (this.valueType == 'url' && this.fileMax == 1) {
            me.$emit('change', me.files && me.files.length > 0 ? me.files[0].url : '', me.files, me.fileIds.join(","), me.removeIds)
          } else {
            me.$emit('change', me.files && me.files.length > 0 ? JSON.stringify(me.files) : '', me.files, me.fileIds.join(","), me.removeIds)
          }

        }
      }
    },
    mounted() {

    },
    created() {
      this.$nextTick(function() {
          this.isUpload = false
          if (this.value != '' && typeof this.value == 'string') {
            this.fileList.push({
              uid: '-1',
              name: 'file',
              url: this.value
            })
          }
          if (this.value != '' && typeof this.value == 'object') {
            this.fileList = this.value
          }
          this.init()
        }
      )
    }
  }
</script>

<style lang="less">
  .ant-upload-list-picture-card .ant-upload-list-item {
    width: 70px;
    height: 70px;
  }

  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload.ant-upload-select-picture-card {
    width: 70px;
    height: 70px;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>

